package com.study.job;

import com.study.service.LicenceCheckService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author CSDN 流放深圳
 * @description 定时任务
 * @create 2024-04-13 15:55
 * @since 1.0.0
 */
@Component
public class LicenceJob {

    private static Logger log = LoggerFactory.getLogger(LicenceJob.class);

    private SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private LicenceCheckService licenceCheckService;

    /**
     * 定时任务（权衡服务性能和更换证书，将执行频率设定为 10 分钟，更换证书的时间等待最长是10分钟）
     */
    @PostConstruct
    public void checkLicence(){
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleAtFixedRate(() -> {
            log.info("***** checkLicence start at " + SDF.format(new Date()) + " *****");
            try {
                Boolean flag = licenceCheckService.checkLicence();
                if (!flag) {
                    log.error("checkLicence flag = " + flag);
                }else{
                    log.info("checkLicence flag = " + flag);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }, 0, 10, TimeUnit.MINUTES); // 延迟0秒后首次执行，之后每 10 分钟执行一次
    }

}
